import SearchTable from '@/components/common/SearchTable';
import DealerDetailModel from '@/components/Dealer/dealerDetailModel';
import Ellipsis from '@/components/Ellipsis';
import { getDicByKey } from '@/support/common';
import { connect } from 'dva';
import moment from 'moment/moment';
import PropTypes from 'prop-types';
import React, { createRef } from 'react';
import MaskText from '@/components/MaskText';

@connect()
class Page extends React.Component {
  static contextTypes = {
    dicData: PropTypes.any,
    authButton: PropTypes.array,
  };

  formRef = null;
  tableRef = createRef();

  state = {
    detailVisible: false,
    detailModelData: {},
    brandOptions: [],
    areaOptions: [],
    smallAreaOptions: [],
  };

  componentDidMount() {
    this.initBrand();
    // this.initBrand2();
  }

  onSource = (page, size, args) =>
    new Promise(resolve => {
      this.props.dispatch({
        type: 'http/getData',
        payload: {
          url: '/dealer/list',
          page: page - 1,
          size,
          ...args,
        },
        callback: res => {
          if (res && res.statusCode === '0') {
            resolve({
              total: res.data.pagination.total,
              data: res.data.list,
            });
          } else {
            resolve({
              total: 0,
              data: [],
            });
          }
        },
      });
    });

  initBrand = () => {
    this.props.dispatch({
      type: 'basedata/brandFetch',
      payload: { url: '/dealer/brand' },
      callback: res => {
        if (res.data && res.data.length) {
          this.setState({ brandOptions: res.data });
          this.formRef.current.setFieldsValue({ brandCode: res.data[0].brandCode });
          this.tableRef.current.refresh();
          this.handleArea(res.data[0].brandCode);
        }
      },
    });
  };

  // initBrand2 = () => {
  //   this.props.dispatch({
  //     type: 'http/getDataWithRes',
  //     payload: { url: '/datapermission/finditemlist2', dataPermissionType: 'BRAND' },
  //     callback: res => {
  //       if (res && res.data && res.data.length > 0) {
  //         console.log('222222');
  //         this.setState({ brandOptions: res.data });
  //         this.formRef.current.setFieldsValue({ brandCode: res.data[0].dataPermissionItemValue });
  //         this.tableRef.current.refresh();
  //         this.handleArea(res.data[0].dataPermissionItemValue);
  //       }
  //     },
  //   });
  // };

  handleArea = brandCode => {
    const { dispatch } = this.props;
    this.setState({
      areaOptions: [],
      smallAreaOptions: [],
    });
    this.formRef.current.resetFields(['areaId', 'smallAreaId']);
    if (brandCode) {
      dispatch({
        type: 'common/queryListGet',
        payload: { url: '/dealer/getareabybrand', brandId: brandCode },
        callback: data => {
          if (data) {
            this.setState({ areaOptions: data });
          }
        },
      });
    }
  };

  handleSmallArea = areaId => {
    const { dispatch } = this.props;
    this.setState({
      smallAreaOptions: [],
    });
    this.formRef.current.resetFields(['smallAreaId']);
    if (areaId) {
      dispatch({
        type: 'common/queryListGet',
        payload: { url: '/dealer/getsmallareabyarea', areaId: areaId },
        callback: data => {
          if (data) {
            this.setState({ smallAreaOptions: data });
          }
        },
      });
    }
  };

  handleFormReset = () => {
    if (this.state.brandOptions && this.state.brandOptions.length) {
      this.formRef.current.setFieldsValue({
        brandCode: this.state.brandOptions[0].dataPermissionItemValue,
      });
      this.handleArea(this.state.brandOptions[0].dataPermissionItemValue);
      this.tableRef.current.refresh();
    }
    return false;
  };

  render() {
    const searchItems = [
      {
        title: '品牌',
        type: 'select',
        key: 'brandCode',
        rules: [{ required: true, message: '请选择' }],
        options: this.state.brandOptions.map(e => ({
          label: e.brandName,
          value: e.brandCode,
        })),
        onChange: this.handleArea,
      },
      {
        title: '大区',
        type: 'select',
        key: 'areaId',
        options: this.state.areaOptions.map(e => ({ label: e.descript, value: e.code })),
        onChange: this.handleSmallArea,
      },
      {
        title: '小区',
        type: 'select',
        key: 'smallAreaId',
        options: this.state.smallAreaOptions.map(e => ({ label: e.descript, value: e.code })),
      },
      {
        title: '经销商代码',
        type: 'input',
        key: 'code',
      },
      {
        title: '经销商名称',
        type: 'input',
        key: 'name',
      },
    ];
    const columns = [
      {
        title: '经销商代码',
        dataIndex: 'code',
      },
      {
        title: '经销商名称',
        dataIndex: 'name',
        render: val => (
          <Ellipsis length={12} tooltip>
            {val}
          </Ellipsis>
        ),
      },
      {
        title: '经销商简称',
        dataIndex: 'shortName',
        render: val => (
          <Ellipsis length={6} tooltip>
            {val}
          </Ellipsis>
        ),
      },
      {
        title: '大区',
        dataIndex: 'areaId',
        render: (text, record) => getDicByKey(this.context.dicData, `${record.brandId}area`, text),
      },
      {
        title: '小区',
        dataIndex: 'smallAreaId',
        render: (text, record) =>
          getDicByKey(this.context.dicData, `${record.brandId}village`, text),
      },
      {
        title: '经销商电话',
        dataIndex: 'phone',
        render(val) {
          return <MaskText text={val} type={'landline'} />;
        },
      },
      {
        title: '地址',
        dataIndex: 'address',
        render(val) {
          return <MaskText text={val} type="location" />;
        },
      },
      {
        title: '展车数量',
        dataIndex: 'showCar',
      },
      {
        title: '经销商状态',
        dataIndex: 'status',
        render: text => {
          return text != null ? getDicByKey(this.context.dicData, 'dealerStatus', text + '') : '';
        },
      },
      {
        title: '建立时间',
        dataIndex: 'openTime',
        render: text => {
          return text != null ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '';
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 140,
        fixed: 'right',
        render: (text, record) => {
          return (
            <div>
              <span>
                <a onClick={() => this.setState({ detailVisible: true, detailModelData: record })}>
                  详情
                </a>
              </span>
            </div>
          );
        },
      },
    ];
    return (
      <>
        <SearchTable
          ref={this.tableRef}
          initRefresh={false}
          searchProps={{
            onRef: e => {
              this.formRef = e;
            },
            handleFormReset: this.handleFormReset,
            searchItems,
          }}
          tableProps={{
            rowKey: 'sid',
            // size: 'small',
            onSource: this.onSource,
            columns,
            scroll: { x: true },
          }}
        />
        <DealerDetailModel
          changeVisible={() => this.setState({ detailVisible: false, detailModelData: {} })}
          visible={this.state.detailVisible}
          detailModelData={this.state.detailModelData}
          dispatch={this.props.dispatch}
        />
      </>
    );
  }
}

export default Page;
